<template>
  <el-container style="background-color: white;">
    <el-main>
      <!-- 表单区域 -->
      <el-form :inline="true" label-width="100px">
        <el-form-item label="生产单号:">
          <el-input v-model="searchParams.orderNumber" placeholder="请输入生产单号"></el-input>
        </el-form-item>
        <el-form-item label="商品信息:">
          <el-input v-model="searchParams.productInfo" placeholder="请输入条码、名称、规格、型号" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="单据日期:">
          <el-date-picker
            v-model="searchParams.singleDateStart"
            type="datetime"
            placeholder="开始时间"
          ></el-date-picker>
          ~
          <el-date-picker
            v-model="searchParams.singleDateEnd"
            type="datetime"
            placeholder="结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="toggleAdvancedSearch">
            {{ advancedSearchVisible ? '收起' : '展开' }}
            <i :class="advancedSearchVisible ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
          </el-button>
        </el-form-item>

        <!-- 高级搜索条件 -->
        <div v-show="advancedSearchVisible">
          <el-form-item label="销售订单号:">
            <el-input v-model="searchParams.salesOrderNumber" placeholder="请输入销售订单号"></el-input>
          </el-form-item>
          <el-form-item label="计划完工:">
            <el-date-picker
              v-model="searchParams.planCompletionStart"
              type="datetime"
              placeholder="开始时间"
            ></el-date-picker>
            ~
            <el-date-picker
              v-model="searchParams.planCompletionEnd"
              type="datetime"
              placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="单据状态:">
            <el-select v-model="searchParams.singleStatus" placeholder="请选择">
              <el-option label="全部" value=""></el-option>
              <el-option label="未审核" value="0"></el-option>
              <el-option label="加工中" value="1"></el-option>
              <el-option label="已完工" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户原始单号:">
            <el-input v-model="searchParams.customerOriginalNumber" placeholder="请输入客户原始单号"></el-input>
          </el-form-item>
        </div>
      </el-form>

      <!-- 操作按钮区域 -->
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="openAddDialog">+ 新增</el-button>
<!--        <el-button type="primary">+ 批量新增</el-button>-->
        <el-button @click="handleBatchDelete" :disabled="selectedRows.length === 0">删除</el-button>
        <el-button>审核</el-button>
        <el-button>反审核</el-button>
        <el-button>重新加工</el-button>
      </div>

      <!-- 弹窗组件 -->
      <ProductionTaskAddDialog ref="addDialog" @save-success="fetchProductionTasks"/>

      <!-- 表格区域 -->
      <el-table :data="productionTasks" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="operation" label="操作" width="80">
          <template slot-scope="scope">
            <span
              v-if="scope.row.status === 0"
              class="operation-link"
              @click="handleEdit(scope.$index, scope.row)"
            >
              编辑
            </span>
            <span
              v-if="scope.row.status === 1"
              class="operation-link"
              @click="handleProcess(scope.$index, scope.row)"
            >
              加工
            </span>
            <span
              v-if="scope.row.status === 2"
              class="operation-link"
              @click="handleView(scope.$index, scope.row)"
            >
              查看
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNumber" label="生产单号" ></el-table-column>
        <el-table-column prop="salesOrderNumber" label="销售订单号"></el-table-column>
        <el-table-column prop="productBarcode" label="商品条码"></el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="standard" label="商品规格"></el-table-column>
        <el-table-column prop="model" label="商品型号"></el-table-column>
        <el-table-column prop="orderedQuantity" label="订购数量"></el-table-column>
        <el-table-column prop="producedQuantity" label="生产数量"></el-table-column>
        <el-table-column prop="plannedCompletionDate" label="计划完工日期"></el-table-column>
        <el-table-column prop="documentDate" label="单据日期"></el-table-column>
        <el-table-column prop="operatorId" label="操作员">
          <template slot-scope="scope">
            {{ getResponsiblePersonName(scope.row.operatorId) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 0">未审核</span>
            <span v-else-if="scope.row.status === 1">加工中</span>
            <span v-else-if="scope.row.status === 2">已完工</span>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 16px; text-align: right;"
      >
      </el-pagination>
    </el-main>
  </el-container>
</template>

<script>
import ProductionTaskAddDialog from '@views/production/ProductionTaskAddDialog.vue';
import {getAction, postAction} from "@api/manage";
import {getUserList} from "@api/api";

export default {
  name: 'ProductionTask',
  components: {
    ProductionTaskAddDialog
  },
  data() {
    return {
      // 添加展开收起状态
      advancedSearchVisible: false,
      productionTasks: [],
      responsiblePersonList:[],
      // 添加已选中的行数据
      selectedRows: [],
      searchParams: {
        orderNumber: '',
        productInfo: '',
        singleDateStart: '',
        singleDateEnd: '',
        salesOrderNumber: '',
        planCompletionStart: '',
        planCompletionEnd: '',
        singleStatus: '',
        customerOriginalNumber: '',
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  methods: {
    handleSearch() {
      // 查询逻辑
      this.pagination.current = 1;
      this.fetchProductionTasks();
    },
    // 添加重置方法
    handleReset() {
      this.searchParams = {
        orderNumber: '',
        productInfo: '',
        singleDateStart: '',
        singleDateEnd: '',
        salesOrderNumber: '',
        planCompletionStart: '',
        planCompletionEnd: '',
        singleStatus: '',
        customerOriginalNumber: '',
      };
      // 重置后重新查询
      this.pagination.current = 1;
      this.fetchProductionTasks();
    },
    // 添加展开收起切换方法
    toggleAdvancedSearch() {
      this.advancedSearchVisible = !this.advancedSearchVisible;
    },
    handleView(index, row) {
      // 查看逻辑
    },
    handleEdit(index, row) {
      // 编辑逻辑
      this.$refs.addDialog.openDialog(row);
    },
    // 添加批量删除方法
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'warning'
        });
        return;
      }
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "此操作将永久删除选中的生产任务, 是否继续?",
        onOk: function () {
          postAction('/production/task/delete', that.selectedRows).then((res) => {
            if (res.code === 200) {
              that.$message.success('删除成功');
              // 重新获取数据
              that.fetchProductionTasks();
              // 清空选中项
              that.selectedRows = [];
            } else {
              that.$message.error('删除失败');
            }
          }).catch((err) => {
            console.error('Error deleting production processes:', err);
            that.$message.error('删除失败');
          });
        }
      });
    },
    handleProcess(index, row) {
      // 加工逻辑
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.current = 1;
      this.fetchProductionTasks();
    },
    handleCurrentChange(val) {
      this.pagination.current = val;
      this.fetchProductionTasks();
    },
    // 获取生产任务列表数据
    fetchProductionTasks() {
      const params = {
        search: JSON.stringify({
          ...this.searchParams,
        }),
        currentPage: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      getAction('/production/task/list', params).then((res) => {
        console.log('res', res);
        if (res.code === 200) {
          this.productionTasks = res.data.rows;
          this.pagination.total = res.data.total;
        } else {
          console.error('Failed to fetch product data:', res);
        }
      }).catch((err) => {
        console.error('Error fetching product data:', err);
      });
    },
    initUser() {
      getUserList({}).then((res)=>{
        if(res) {
          this.responsiblePersonList = res;
        }
      });
    },
    getResponsiblePersonName(id) {
      const person = this.responsiblePersonList.find(item => item.id === id);
      return person ? person.userName : id;
    },
    openAddDialog() {
      this.$refs.addDialog.openDialog();
    },
    // 添加处理选中行变化的方法
    handleSelectionChange(selection) {
      this.selectedRows = selection.map(item => item.id);
    },
  },
  mounted() {
    // 页面加载时获取初始数据
    this.fetchProductionTasks();
    this.initUser();
  }
};
</script>
<style scoped>
.operation-link {
  color: #409EFF;
  text-decoration: underline;
  cursor: pointer;
  margin-right: 10px;
}

.operation-link:hover {
  color: #66b1ff;
}

.operation-link.is-disabled {
  color: #C0C4CC;
  cursor: not-allowed;
}

.operation-link.danger {
  color: #F56C6C;
}

.operation-link.danger:hover {
  color: #f78989;
}
</style>